#############################################################################
# Copyright (c) 2009 Dmitry Grushin <dgrushin@gmail.com>.
#
# This file is part of clupower (cluster power manager utility)
#
# Clupower is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Clupower is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Clupower.  If not, see <http://www.gnu.org/licenses/>.
#
# Contributors:
#    Dmitry Grushin <dgrushin@gmail.com> - initial API and implementation
#############################################################################

require 'socket'
require 'settings'
require 'errors'
require 'cputil'

class CPClient

  def shutdown(leave_nodes=false)
    s = send_shutdown(leave_nodes)
    puts "Send shutdown command. Wait for power manager completion. It may take some time... "
    puts s.readline
    s.close
  rescue CPRuntimeError => e
    raise CPI4.new.set_cause(e)
  end

  # Sends reload command and returns server response
  def reload
    key = get_key
    stream_sock = get_sock
    stream_sock.write("RELOAD#{key}")
    return stream_sock.readline
  end

  def send_shutdown(leave_nodes)
    key = get_key
    stream_sock = get_sock
    if leave_nodes
      cmd = "EXIT#{key}"
    else
      cmd = "STOP#{key}"
    end
    stream_sock.write(cmd)
    return stream_sock
  end

  # Request server status
  def status
    key = get_key
    stream_sock = get_sock
    cmd = "STATUS#{key}"
    stream_sock.write(cmd)
    return stream_sock.readline
  end

  def node_status(node)
    key = get_key
    stream_sock = get_sock
    cmd = "NODESTATUS#{key}#{node}"
    stream_sock.write(cmd)
    return stream_sock.readline
  end

  private

  def get_key
    lock_file = Utils.get_lock_file
    if !File.exist?(lock_file)
      raise CPI8.new(lock_file)
    end
    if !File.owned?(lock_file)
      raise CPI5.new
    end
    f = open(lock_file)
    if key = f.gets
      return key.chomp!
    end
    raise CPI6.new(lock_file)
  end

  def get_sock
    return TCPSocket.new("127.0.0.1", Settings.instance.get('SERVER_PORT'))
  end
end
